import express from "express";
import morgan from "morgan";
import path from "path";
import fs from "fs";

const app = express();
const PORT = process.env.PORT || 3000;

// 使用morgan记录请求日志
app.use(morgan("dev"));

// 设置静态文件目录
const publicDir = path.join(__dirname, "../public");
// app.use(express.static(publicDir, {
//   setHeaders: (res, filePath) => {
//     if (path.extname(filePath) === '.ts') {
//       res.setHeader('Content-Type', 'video/mp2t');
//     }
//   }
// }));

// 主页路由
app.get("/", (req, res) => {
  res.send(`
        <h1>Welcome to the Huiguo Player</h1>
        <p>Click <a href="/play">here</a> to play the Video files.</p>
    `);
});

// 播放页面路由
app.get("/play", (req, res) => {
  const tsFiles = getTsFiles(path.join(publicDir, 'v'));
  const videoList = tsFiles.map(file => `<li><a href="/play/${file}">${file}</a></li>`).join("");

  res.send(`
        <h1>Video Files</h1>
        <ul>
            ${videoList}
        </ul>
    `);
});

// 渲染包含播放器的页面
app.get('/play/:filename', (req, res) => {
  const filename = req.params.filename;
  const filePath = `/video/${filename}`;

  const html = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Video Player</title>
      <link href="https://vjs.zencdn.net/7.11.4/video-js.css" rel="stylesheet" />
  </head>
  <body>
      <h1>Video Player</h1>
      <video id="my-video" class="video-js" controls preload="auto" width="640" height="360" data-setup="{}">
          <source src="${filePath}">
          <p class="vjs-no-js">
              To view this video please enable JavaScript, and consider upgrading to a web browser that
              <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
          </p>
      </video>
      <script src="https://vjs.zencdn.net/7.11.4/video.js"></script>
  </body>
  </html>
  `;

  res.send(html);
});



app.get('/video/:filename', (req, res) => {
  const filename = req.params.filename;
  const filePath = path.join(publicDir, 'v', filename);
  const stat = fs.statSync(filePath);

  const range = req.headers.range;
  if (range) {
    const parts = range.replace(/bytes=/, "").split("-");
    const start = parseInt(parts[0], 10);
    const end = parts[1] ? parseInt(parts[1], 10) : stat.size - 1;

    const chunkSize = (end - start) + 1;
    const file = fs.createReadStream(filePath, { start, end });

    res.writeHead(206, {
      'Content-Range': `bytes ${start}-${end}/${stat.size}`,
      'Accept-Ranges': 'bytes',
      'Content-Length': chunkSize,
      'Content-Type': 'video/mp4',
    });

    file.pipe(res);
  } else {
    res.writeHead(200, {
      'Content-Length': stat.size,
      'Content-Type': 'video/mp4',
    });
    fs.createReadStream(filePath).pipe(res);
  }
});

// 获取指定目录下的所有 .ts 文件
const getTsFiles = (dir: string) => {
  const files = fs.readdirSync(dir);
  return files.filter(file => file.endsWith(".ts") || file.endsWith(".mp4"));
}

// 启动服务器
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});
